package com.changgou.goods.service.impl;

import com.alibaba.fastjson.JSON;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.goods.dao.BrandMapper;
import com.changgou.goods.dao.CategoryMapper;
import com.changgou.goods.dao.SkuMapper;
import com.changgou.goods.dao.SpuMapper;
import com.changgou.goods.pojo.*;
import com.changgou.goods.service.SpuService;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SpuServiceImpl implements SpuService {

    @Autowired
    private SpuMapper spuMapper;

    @Autowired
    private SkuMapper skuMapper;

    @Autowired
    private IdWorker idWorker;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private BrandMapper brandMapper;

    /**
     * 查询全部列表
     *
     * @return
     */
    @Override
    public List<Spu> findAll() {
        return spuMapper.selectAll();
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public Goods findById(String id) {
        //new一个要返回的goods对象
        Goods goods = new Goods();

        //根据传入的id查询spu填入goods
        Spu spu = spuMapper.selectByPrimaryKey(id);
        goods.setSpu(spu);

        //根据传入的id构建sku的example条件查询出skuList填入goods
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();//生成条件
        criteria.andEqualTo("spuId", id);
        List<Sku> skuList = skuMapper.selectByExample(example);

        goods.setSkuList(skuList);

        return goods;

    }

    /**
     * 增加
     *
     * @param goods
     */

    @Override
    @Transactional
    public Result add(Goods goods) {
        //对于传入的goods对象进行分布存储
        //先存spu部分
        Spu spu = goods.getSpu();
        //给spu设置一个分布式id
        spu.setId(String.valueOf(idWorker.nextId()));
        spuMapper.insertSelective(spu);


        //再存入skuList到sku表中根据传入的goods获取skuList,批量插入sku
        if (insertSkuList(goods.getSkuList())) {
            return new Result(true, StatusCode.OK, "批量成功");
        } else {
            return new Result(false, StatusCode.ERROR, "批量失败,传入skuList为空");
        }
    }


    /**
     * 修改
     *
     * @param goods
     */
    @Override
    @Transactional
    public Result update(Goods goods) {
        //根据传入goods获取spu,并更新到spu表中
        Spu spu = goods.getSpu();
        spuMapper.updateByPrimaryKeySelective(spu);


        //根据spuId删除原spu下的所有sku
        Example example = new Example(Sku.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("spuId", spu.getId());
        int i = skuMapper.deleteByExample(example);
        System.out.println("条件删除了" + i + "条sku记录");


        //根据传入的goods获取skuList,批量插入sku
        if (insertSkuList(goods.getSkuList())) {
            return new Result(true, StatusCode.OK, "批量成功");
        } else {
            return new Result(false, StatusCode.ERROR, "批量失败,传入skuList为空");
        }

    }


    /**
     * 删除
     *
     * @param id
     */
    @Override
    public void delete(String id) {
        spuMapper.deleteByPrimaryKey(id);
    }


    /**
     * 条件查询
     *
     * @param searchMap
     * @return
     */
    @Override
    public List<Spu> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return spuMapper.selectByExample(example);
    }

    /**
     * 分页查询
     *
     * @param page
     * @param size
     * @return
     */
    @Override
    public Page<Spu> findPage(int page, int size) {
        PageHelper.startPage(page, size);
        return (Page<Spu>) spuMapper.selectAll();
    }

    /**
     * 条件+分页查询
     *
     * @param searchMap 查询条件
     * @param page      页码
     * @param size      页大小
     * @return 分页结果
     */
    @Override
    public Page<Spu> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page, size);
        Example example = createExample(searchMap);
        return (Page<Spu>) spuMapper.selectByExample(example);
    }


    /**
     * 审核商品
     *
     * @param id
     * @return
     */
    @Override
    public void CheckSpu(String id) {

        //查询spu对象
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("当前商品不存在");
        }
        //判断当前spu是否处于删除状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品处于删除状态");
        }
        //不处于删除状态,修改审核状态为1,上下架状态为1
        spu.setStatus("1");
        spu.setIsMarketable("1");
        //执行修改操作
        spuMapper.updateByPrimaryKeySelective(spu);

    }

    /**
     * 下架商品
     *
     * @param id
     */
    @Override
    public void pull(String id) {
        //查询spu
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu == null) {
            throw new RuntimeException("当前商品不存在");
        }
        //判断当前商品是否处于删除状态
        if ("1".equals(spu.getIsDelete())) {
            throw new RuntimeException("当前商品处于删除状态");
        }
        //商品处于未删除状态的话,则修改上下架状态为已下架(0)
        spu.setIsMarketable("0");
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 上架商品
     *
     * @param id
     */
    @Override
    public void put(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        if (spu.getStatus().equals("0")) {
            throw new RuntimeException("未通过审核的商品不能上架！");
        }
        spu.setIsMarketable("1");//设置上架状态
        spuMapper.updateByPrimaryKeySelective(spu);
    }


    /**
     * 商品恢复
     *
     * @param id
     */
    @Override
    public void restore(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //检查是否删除的商品
        if (!spu.getIsDelete().equals("1")) {
            throw new RuntimeException("此商品未删除！");
        }
        spu.setIsDelete("0");
        //未删除
        spu.setStatus("0");
        //未审核
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 物理删除
     *
     * @param id
     */
    @Override
    public void realDelete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //检查是否删除的商品
        if (!spu.getIsDelete().equals("1")) {
            throw new RuntimeException("此商品未删除！");
        }
        spuMapper.deleteByPrimaryKey(id);
    }


    /*** 删除 * @param id */
    @Override
    public void logicDelete(String id) {
        Spu spu = spuMapper.selectByPrimaryKey(id);
        //检查是否下架的商品
        if (!spu.getIsMarketable().equals("0")) {
            throw new RuntimeException("必须先下架再删除！");
        }
        spu.setIsDelete("1");
        //删除
        spu.setStatus("0");
        //未审核
        spuMapper.updateByPrimaryKeySelective(spu);
    }

    /**
     * 构建查询对象
     *
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap) {
        Example example = new Example(Spu.class);
        Example.Criteria criteria = example.createCriteria();
        if (searchMap != null) {
            // 主键
            if (searchMap.get("id") != null && !"".equals(searchMap.get("id"))) {
                criteria.andEqualTo("id", searchMap.get("id"));
            }
            // 货号
            if (searchMap.get("sn") != null && !"".equals(searchMap.get("sn"))) {
                criteria.andEqualTo("sn", searchMap.get("sn"));
            }
            // SPU名
            if (searchMap.get("name") != null && !"".equals(searchMap.get("name"))) {
                criteria.andLike("name", "%" + searchMap.get("name") + "%");
            }
            // 副标题
            if (searchMap.get("caption") != null && !"".equals(searchMap.get("caption"))) {
                criteria.andLike("caption", "%" + searchMap.get("caption") + "%");
            }
            // 图片
            if (searchMap.get("image") != null && !"".equals(searchMap.get("image"))) {
                criteria.andLike("image", "%" + searchMap.get("image") + "%");
            }
            // 图片列表
            if (searchMap.get("images") != null && !"".equals(searchMap.get("images"))) {
                criteria.andLike("images", "%" + searchMap.get("images") + "%");
            }
            // 售后服务
            if (searchMap.get("saleService") != null && !"".equals(searchMap.get("saleService"))) {
                criteria.andLike("saleService", "%" + searchMap.get("saleService") + "%");
            }
            // 介绍
            if (searchMap.get("introduction") != null && !"".equals(searchMap.get("introduction"))) {
                criteria.andLike("introduction", "%" + searchMap.get("introduction") + "%");
            }
            // 规格列表
            if (searchMap.get("specItems") != null && !"".equals(searchMap.get("specItems"))) {
                criteria.andLike("specItems", "%" + searchMap.get("specItems") + "%");
            }
            // 参数列表
            if (searchMap.get("paraItems") != null && !"".equals(searchMap.get("paraItems"))) {
                criteria.andLike("paraItems", "%" + searchMap.get("paraItems") + "%");
            }
            // 是否上架
            if (searchMap.get("isMarketable") != null && !"".equals(searchMap.get("isMarketable"))) {
                criteria.andEqualTo("isMarketable", searchMap.get("isMarketable"));
            }
            // 是否启用规格
            if (searchMap.get("isEnableSpec") != null && !"".equals(searchMap.get("isEnableSpec"))) {
                criteria.andEqualTo("isEnableSpec", searchMap.get("isEnableSpec"));
            }
            // 是否删除
            if (searchMap.get("isDelete") != null && !"".equals(searchMap.get("isDelete"))) {
                criteria.andEqualTo("isDelete", searchMap.get("isDelete"));
            }
            // 审核状态
            if (searchMap.get("status") != null && !"".equals(searchMap.get("status"))) {
                criteria.andEqualTo("status", searchMap.get("status"));
            }

            // 品牌ID
            if (searchMap.get("brandId") != null) {
                criteria.andEqualTo("brandId", searchMap.get("brandId"));
            }
            // 一级分类
            if (searchMap.get("category1Id") != null) {
                criteria.andEqualTo("category1Id", searchMap.get("category1Id"));
            }
            // 二级分类
            if (searchMap.get("category2Id") != null) {
                criteria.andEqualTo("category2Id", searchMap.get("category2Id"));
            }
            // 三级分类
            if (searchMap.get("category3Id") != null) {
                criteria.andEqualTo("category3Id", searchMap.get("category3Id"));
            }
            // 模板ID
            if (searchMap.get("templateId") != null) {
                criteria.andEqualTo("templateId", searchMap.get("templateId"));
            }
            // 运费模板id
            if (searchMap.get("freightId") != null) {
                criteria.andEqualTo("freightId", searchMap.get("freightId"));
            }
            // 销量
            if (searchMap.get("saleNum") != null) {
                criteria.andEqualTo("saleNum", searchMap.get("saleNum"));
            }
            // 评论数
            if (searchMap.get("commentNum") != null) {
                criteria.andEqualTo("commentNum", searchMap.get("commentNum"));
            }

        }
        return example;
    }


    //遍历传入的list中的sku,并设置信息,批量存入sku表中
    private boolean insertSkuList(List<Sku> skuList) {
        //首先判断传入集合不为空并且长度大于0
        if (skuList == null || skuList.size() == 0) {
            return false;
        }
        //根据spuid获取brand和category的对象
        String spuId = skuList.get(0).getSpuId();
        Spu spu = spuMapper.selectByPrimaryKey(spuId);
        Brand brand = brandMapper.selectByPrimaryKey(spu.getBrandId());
        Category category = categoryMapper.selectByPrimaryKey(spu.getCategory3Id());
        //遍历list
        for (Sku sku : skuList) {
            System.out.println(sku);
            //设置sku的分布式id
            sku.setId(String.valueOf(idWorker.nextId()));
            String spec = sku.getSpec();
            if (spec.length() > 0) {
                //如果规格参数存在,则讲spec中的关键词拼接到name里,用于搜索
                String name = sku.getName();
                //遍历specMap,拼接name
                Map<String, String> specMap = JSON.parseObject(spec, Map.class);
                for (String s : specMap.values()) {
                    name += " " + s;
                }
                ;
                sku.setName(name);//设置sku的name

            } else {
                //规格参数不存在,设置空字符串
                sku.setSpec("{}");
            }
            sku.setBrandName(brand.getName());
            sku.setCategoryName(category.getName());
            sku.setCreateTime(new Date());
            //设置了id,spec,name,brandName,CategoryName,CreateTime
            System.out.println(sku);
        }

        return skuMapper.insertBatch(skuList);


    }
}
